<?php

namespace Home\Controller;


class CartController extends CommonController
{
    /**
     * 购物车首页
     */
    public function index()
    {
        $id = $_SESSION['customer']['id'];
        $carts = $this->cart->where("customer_id = '$id'")->select();

        //如果购物车为空，跳转到空购物车页面
        if (empty($carts)) {
            $this->redirect("Cart/em");
        }
        foreach ($carts as &$cart) {
            $cart['product'] = $this->product->where("id = '$cart[product_id]'")->find();
        }

        $this->assign(compact('carts'));
        $this->display();
    }


    /**
     * 添加购物车和立刻购买
     */
    public function add()
    {
        if (IS_AJAX) {
            $data['product_id'] = I('post.product_id');
            $data['customer_id'] = $_SESSION['customer']['id'];
            if (!$_SESSION['customer']) {
                //登录之后跳回当前页面
//                $_SESSION['url'] = "/Home/Index/show/id/" . $data['product_id'] . ".html";
                $info = array('status' => 0, 'msg' => '请登录');
            } else {
                $product = $this->cart->where($data)->setInc('num');
                //查询购物车是否存在要添加的商品，存在就加1,不存在添加商品
                if (!$product) {
                    $this->cart->add($data);
                }
                $info = array('status' => 1, 'msg' => '添加购物车成功');
            }
            $this->ajaxReturn($info);
        }
    }

    /**
     * 购物车增加数量
     */
    public function ajax_add()
    {
        if (IS_AJAX) {
            $id = I('post.id');
            $this->cart->where("id = '$id'")->setInc('num');
        }
    }

    /**
     * 购物车减少数量
     */
    public function ajax_sub()
    {
        if (IS_AJAX) {
            $id = I('post.id');
            $this->cart->where("id = '$id'")->setDec('num');
        }
    }

    /*
     * 改变购物车数量
     */
    public function ajax_num()
    {
        if (IS_AJAX) {
            $id = I('post.id');
            $num = I('post.num');
            $this->cart->where("id = '$id'")->setField('num', $num);
        }
    }

    /**
     * 移除商品
     */
    public function ajax_delete()
    {
        if (IS_AJAX) {
            $id = I('post.id');
            $this->cart->where("id = '$id'")->delete();
        }
    }

    /**
     * 空购物车跳转页面
     */
    public function em()
    {
        $this->display();
    }


}